#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# handlers.py
import re,time,json,logging,hashlib,base64,asyncio

from route import get,post

from models import User,Comment,Blog,next_id

@get('/')
def index(request):
	users = yield from User.findAll()
	return {
		'__template__':'test.html',
		'users':users
	}

@get('/api/users')
def api_get_users(*,page='1'):
	page_index = get_page_index(page)
	num = yield from User.findNumber('count(id)')
	p = Page(num,page_index)
	if num ==0:
		return dict(page=p,users=())
	users = yield from findAll(orderBy = 'created_at desc',limit=(p.offset,p.limit))
	for u in users:
		u.passwd = '******'
	return dict(page = p, users = users)

_RE_EMAIL = re.compile(r'^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$')
_RE_SHA1  = re.compile(r'^[0-9a-f]{40}$')

@post('/api/users')
def api_register_user(*,email,name,passwd):
	if not name or not name.strip():
		raise APIValueError('name')
	if not email or not _RE_EMAIL.match(email):
		raise APIValueError('email')
	if not passwd or not _RE_SHA1.match(passwd):
		raise APIValueError('passwd')
	users = yield from User.findAll('email=?',[email])
	if len(user)>0:
		raise APIError('register:failed','email','Email is already in use')
	uid = next_id()
	sha1_passwd = '%s:%s' %(uid,passwd)
	user = User(id=uid,name=name.strip(),email=email,passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(),image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest())
	yield from user.save()

	r= web.Response()
	r.set_cookie(COOKIE_NAME,user2cookie(user,86400),max_age=86400,httponly=True)
	user.passwd = '******'
	r.content_type = 'application/json'
	r.body = json.dumps(user,ensure_ascii=False).encode('utf-8')
	return r

@post('/api/blogs')
def api_create_blog(request,*,name,summary,content):
	check_admin(request)
	if not name or not name.strip():
		raise APIValueError('name', 'name cannot be empty.')
	if not summary or not summary.strip():
		raise APIValueError('summary', 'summary cannot be empty.')
	if not content or not content.strip():
		raise APIValueError('content', 'content cannot be empty.')
	blog = Blog(user_id=request.__user__.id,user_name=request.__user__.name,user_image=request.__user__.image,name=name.strip(),summary=summary.strip(),content=content.strip())
	yield from blog.save()
	return blog



	